package com.homework;

import java.util.concurrent.*;

public class Callable01 {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();

        System.out.println("Main Thread Start!");

        ThreadPoolExecutor t = new ThreadPoolExecutor(1, 2, 2000L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        CompletionService<String> cs = new ExecutorCompletionService<>(t);
        for (int i = 0; i < 10; i++) {
            final int j = i;
            cs.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(1000L);
                    return "result of TaskResult " + j;
                }
            });
        }

        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("异步处理结果为：" + cs.take().get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        t.shutdown();
        System.out.println("Main Thread End!");
    }

}
